package fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.imagesharing.R;
import com.google.android.material.snackbar.Snackbar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;

import adapter.TrendsAdapter;
import entity.XiaoWaiApiBaseInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TrendsFragment extends Fragment {
    private static final String TAG = "MainActivity";
    private static final int NUM_COLUMNS = 1;
    private static final int INIT_IMAGE_NUM = 20;
    private static final int ADD_IMAGE_NUM = 5;
    private static final String REQUEST_MODE = "POST";
    //    protected FragmentActivity rmActivity;
    TrendsAdapter trendsAdapter;
    StaggeredGridLayoutManager staggeredGridLayoutManager;
    RecyclerView recyclerView;


    private LinkedList<String> mImageUrls = new LinkedList<>();
    private LinkedList<String> mSentences = new LinkedList<>();

    SmartRefreshLayout smartRefreshLayout;
    private static final String[] INIT_NAME = {"Havasu Falls", "Trondheim", "Portugal",
            "Rocky Mountain National Park", "Mahahual", "Frozen Lake", "White Sands Desert",
            "Austrailia", "Washington"};

    private TrendsFragment() {
        // Required empty public constructor
    }

    private static TrendsFragment fragment = new TrendsFragment();

    public static TrendsFragment newInstance() {
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_trends, container, false);
        trendsAdapter = new TrendsAdapter(getActivity());
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(NUM_COLUMNS, LinearLayoutManager.VERTICAL);
        recyclerView = v.findViewById(R.id.trend_recyclerView);
        initImageBitmaps();
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        recyclerView.setAdapter(trendsAdapter);
        smartRefreshLayout = v.findViewById(R.id.trend_refresh_parent);

        //下拉刷新
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新时，执行这段
                Log.i(TAG, "onRefresh: 执行了下拉刷新");
                initImageBitmaps();
                smartRefreshLayout.finishRefresh(1000);
            }
        });

        //上拉加载更多
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //上拉加载时，执行这段
                Log.i(TAG, "onLoadMore: 执行了上拉加载");
                for (int i = 0; i < ADD_IMAGE_NUM; i++) {
                    requestMessage();
                }
                smartRefreshLayout.finishLoadMore(1000);
            }
        });

        return v;
    }

    private void initImageBitmaps() {
        Log.d(TAG, "initImageBitmaps: preparing bitmaps.");

        for (int i = 0; i < INIT_IMAGE_NUM; i++) {
            requestMessage();
        }
        if (trendsAdapter != null)
            trendsAdapter.refreshView();
    }


    private void addImage(String url, String imageName) {
        trendsAdapter.add(imageName, url);
    }


    public void requestMessage() {
        XiaoWaiApiBaseInfo apiBaseInfo = XiaoWaiApiBaseInfo.getInstance();
        FormBody.Builder builder = new FormBody.Builder();
        FormBody body = builder.build();
        String[] apiPath = {apiBaseInfo.getBASE_API(), apiBaseInfo.getG_API(), apiBaseInfo.getM_API()};
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(apiPath[new Random().nextInt(apiPath.length)])
                        .get()
                        .addHeader("Content-Type", "application/json")
                        .build();
                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(callback);
                } catch (NetworkOnMainThreadException ex) {
                    ex.printStackTrace();
                }
                Request request2 = new Request.Builder()
                        .url(apiBaseInfo.getWORD_API())
                        .get()
                        .addHeader("Content-Type", "application/json")
                        .build();
                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request2).enqueue(callback_word);
                } catch (NetworkOnMainThreadException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }

    private okhttp3.Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
            Snackbar.make(getActivity().findViewById(R.id.act_trend), "网络请求出错，请检查网络是否异常或稍后再试",
                    Snackbar.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
            TrendsFragment.newInstance().responseMessage(call, response);
        }
    };

    // @Override
    public void responseMessage(Call call, Response responseMessage) throws IOException {

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (responseMessage.code() == 200) {
                    String bodyString = responseMessage.request().url().toString();
                    System.out.println(getActivity());
                    while (mSentences.isEmpty());
                    addImage(bodyString, mSentences.removeLast());

                } else {

                    Snackbar.make(getActivity().findViewById(R.id.act_trend), responseMessage.code() + "错误",
                            Snackbar.LENGTH_SHORT)
                            .show();
//                    addImage("aa","bb");
                }

            }
        });
    }

    private okhttp3.Callback callback_word = new Callback() {
        @Override
        public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
            Snackbar.make(getActivity().findViewById(R.id.act_trend), "网络请求出错，请检查网络是否异常或稍后再试",
                    Snackbar.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (response.code() == 200) {
                        String bodyString = null;
                        try {
                            bodyString = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mSentences.addLast(bodyString);

                    } else {

                        Snackbar.make(getActivity().findViewById(R.id.act_trend), response.code() + "错误",
                                Snackbar.LENGTH_SHORT)
                                .show();
//                    addImage("aa","bb");
                    }
                }
            });
        }
    };


}
